package com.jingtao.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingtao.mapper.ItemDescMapper;
import com.jingtao.mapper.ItemMapper;
import com.jingtao.pojo.Item;
import com.jingtao.pojo.ItemDesc;
import com.jingtao.pojo.User;
import com.jingtao.vo.ItemVO;
import com.jingtao.vo.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImp implements ItemService{

    @Resource
    private ItemMapper itemMapper;
    @Resource
    private ItemDescMapper itemDescMapper;

    /**
     * 要求：3+2记录总数
     *
     * @param pageResult
     * @return
     */
    @Override
    @Transactional
    public PageResult getItemList(PageResult pageResult) {
        //1、构建分页对象  参数1：第几页， 参数2：每页多少条
        Page<Item> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        //2、准备条件构造器 构建模糊查询
        QueryWrapper queryWrapper = new QueryWrapper();
        String query = pageResult.getQuery();
        boolean flag = StringUtils.hasLength(query);
        queryWrapper.like(flag,"title", pageResult.getQuery());
        //根据MP查询 实现分页数据的自动封装
        page = itemMapper.selectPage(page,queryWrapper);
        //获取数据，返回分页对象
        long total = page.getTotal();
        List<Item> rows = page.getRecords();
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
    }

    /**
     * 问题：id是主键自增，入库之后才有主键，所以应该让主键动态回显
     * mybatis动态实现回显
     * MP是mybatis的增强版本，可以实现自动的主键回显
     * @param itemVO
     */
    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item = itemVO.getItem();
        item.setStatus(true);//设定状态
        itemMapper.insert(item);
        //获取商品的详情
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId((item.getId()));
        itemDescMapper.insert(itemDesc);
    }
}
